﻿using DzInfo.Tools;
using Kingdee.BOS.App.Core;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.DzConvert.ZhuMuNiao
{
    [Description("销售订单预收信息带到发货通知单"), HotUpdate]
    public class salConvertfh : AbstractConvertPlugIn
    {
        //public override void OnGetSourceData(GetSourceDataEventArgs e)
        //{
        //    base.OnGetSourceData(e);
        //    List<int> entrids = new List<int>();
        //    var data = e.SourceData;
        //    foreach (var row in data)
        //    {
        //        var eid = Convert.ToInt32(row["FSaleOrderEntry_FEntryID"]);
        //        entrids.Add(eid);
        //    }
        //    var lists = data.Select(s => Convert.ToInt32(s["FSaleOrderEntry_FEntryID"])).ToList();
        //}
        //public override void OnCreateTarget(CreateTargetEventArgs e)
        //{
        //    base.OnCreateTarget(e);
        //    var s = e.GroupingData;
        //    foreach (var ss in s)
        //    {

        //    }
        //}
        public override void AfterConvert(AfterConvertEventArgs e)
        {
            base.AfterConvert(e);
            //var sobj = e.SourceBusinessInfo;
            var tForm = e.TargetBusinessInfo.GetForm();
            if (tForm.LinkSet == null || tForm.LinkSet.LinkEntitys == null || tForm.LinkSet.LinkEntitys.Count == 0)
            {
                return;
            }
            //源单分录ID
            HashSet<long> srcIds = new HashSet<long>();
            //关联主实体
            Entity entity = e.TargetBusinessInfo.GetEntity(tForm.LinkSet.LinkEntitys[0].ParentEntityKey);
            //关联link子实体
            Entity linkEntity = e.TargetBusinessInfo.GetEntity(tForm.LinkSet.LinkEntitys[0].Key);
            var datas = e.Result.FindByEntityKey(entity.Key);
            foreach (var row in datas)
            {
                var linkRows = linkEntity.DynamicProperty.GetValue(row.DataEntity) as DynamicObjectCollection;
                foreach (var linkRow in linkRows)
                {
                    long sid = Convert.ToInt64(linkRow["sbillid"]);
                    srcIds.Add(sid);
                }
            }
            if (srcIds.Count == 0) { return; }
            DynamicObjectCollection skInfos = GetSK(srcIds);
            if (skInfos.Count == 0) { return; }
            var tArray = e.Result.FindByEntityKey("FBillHead");
            IBillView billView = KingdeeTools.CreateBillView(this.Context, e.TargetBusinessInfo.GetForm().Id);
            foreach (var tArr in tArray)
            {
                billView.Model.DataObject = tArr.DataEntity;
                DifyModel(billView, skInfos);
                Entity tEntity = billView.BusinessInfo.GetEntity("F_POSW_Entity_ca9");
                FlexSaveService saveService = new FlexSaveService(this.Context, "Save");
                saveService.BatchSaveEntityFlexObject(billView.BusinessInfo, tEntity, (DynamicObject[])(object)new DynamicObject[1]
                {
                    tArr.DataEntity
                });
            }
        }

        private void DifyModel(IBillView billView, DynamicObjectCollection skInfos)
        {
            var tobj = billView.Model.DataObject;

            var fobj = (tobj["SAL_DELIVERYNOTICEFIN"] as DynamicObjectCollection)[0];
            var jshj = Convert.ToDecimal(fobj["BillAllAmount"]);
            var hj = Convert.ToDecimal(tobj["F_POSW_KYQty2"]);
            if (hj <= jshj)
            {
                billView.Model.SetValue("F_POSW_KYQty2", hj, 0);
            }
            else
            {
                billView.Model.SetValue("F_POSW_KYQty2", jshj, 0);
            }

            //billView.Model.SetValue("F_POSW_KYQty2", hj, 0);
            //billView.Model.DeleteEntryData("F_POSW_Entity_ca9");
            //billView.Model.BatchCreateNewEntryRow("F_POSW_Entity_ca9", skInfos.Count);
            //var eRows = billView.Model.DataObject["POSW_Cust_Entry100002"] as DynamicObjectCollection;
            //for (int i = 0; i < skInfos.Count; i++)
            //{

            //    billView.Model.SetValue("F_POSW_Text_dvn", skInfos[i]["FADVANCENO"], i);
            //    billView.Model.SetValue("FActRecAmount", skInfos[i]["FAMOUNT"], i);
            //}
        }
        /// <summary>
        /// 获取销售订单的预收信息
        /// </summary>
        /// <param name="srcIds"></param>
        /// <returns></returns>
        private DynamicObjectCollection GetSK(HashSet<long> srcIds)
        {
            string eids = string.Join(",", srcIds);
            string sql = string.Format(@"/*dialect*/ 
            SELECT F_POSW_AMOUNT_0JM FAMOUNT,F_POSW_TEXT_JTV FADVANCENO FROM POSW_t_Cust_Entry100001 WHERE FID IN ({0}) ", eids);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }
    }
}
